const express = require('express')
const router = express.Router()
const Category = require('./../models/catrgory')

// 查询列表
router.get('/', async(req, res)=>{
  const { keyword='', page=1, pageSize=10 } = req.query
  const total = await Category.count(
    {
      $or: [
        {'title': {'$regex': keyword, $options: '$i'}}
      ],
    }
  )

  try {
    const categories = await Category.find(
      {
        $or: [
          {'title': {'$regex': keyword, $options: '$i'}}
        ],
      }
    ).skip((parseInt(page) - 1) * parseInt(pageSize)).
    limit(parseInt(pageSize)).
    sort({ '_id': -1 }).
    exec();
    
    res.json({
      code: 200,
      data: {
        lists: categories,
        currentPage: parseInt(page),
        pageSize: pageSize,
        total: total
      }
    })
  } catch (error) {
    res.status(500).json({
      msg: error.message
    })
  }
})


// 创建
router.post('/', async(req, res) => {
  const category = new Category({
    title: req.body.title,
    sort: req.body.sort
  })
  try {
    const newCategory = await category.save()
    res.status(201).json({
      code: 200,
      data: newCategory,
      msg: '新增成功'
    })
  } catch (error) {
    res.status(500).json({ msg: error.message })
  }
})

// 删除
router.delete('/:id',getCategory, async(req, res) => {
  try {
    await res.category.remove()
    res.json({
      code: 200,
      msg: '删除成功'
    })
  } catch (error) {
    res.status(500).json({ msg: error.message })
  }
})

// 定义中间件
// 通过id获取某一项
async function getCategory(req, res, next) {
  try {
    category = await Category.findById(req.params.id)
    if (category == null) {
      return res.status(404).json({ message: 'Cant find Category'})
    }
  } catch(err){
    return res.status(500).json({ message: err.message })
  }

  res.category = category
  next()
}


module.exports = router